package com.example.alipaydemo.Controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.example.alipaydemo.Utils.GlobalBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("test")
public class TestController {
    @Resource
    GlobalBean globalBean;
    @Resource
    AlipayClient alipayClient;

    @RequestMapping("test1")
    public void test1(HttpServletResponse resp) throws AlipayApiException, IOException {
        AlipayTradePagePayRequest  request = new AlipayTradePagePayRequest();
        request.setReturnUrl(globalBean.getReturnUrl());
        request.setNotifyUrl(globalBean.getNotifyUrl());
        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //你自己的订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", UUID.randomUUID().toString().replace("-",""));
        //支付金额，最小值0.01元
        bizContent.put("total_amount",0.01);
        //订单标题，不可使用特殊符号
        bizContent.put("subject", "测试订单");
        //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //设置订单过期时间 传入的是yyyy-MM-dd HH:mm:ss格式的时间表示订单这个时间段过期
        //bizContent.put("time_expire", );
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse  response = alipayClient.pageExecute(request);
        System.out.println(JSON.toJSONString(response));
        //获取返回的结果
        String body = response.getBody();
        resp.setContentType("text/html;charset="+globalBean.getCharset());
        resp.getWriter().write(body);
        resp.getWriter().flush();
        resp.getWriter().close();
    }


    @RequestMapping("returnUrl")
    public void returnUrl(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<String> strings = parameterMap.keySet();
        //获取配置后的参数
        Map<String,String> params = new HashMap<>();
        strings.forEach(o->{
            params.put(o,String.join(",", parameterMap.get(o)));
        });
        //验证参数是否符合规定 不符合代表恶意传参
        try {
            boolean rsaCheckV1 = AlipaySignature.rsaCheckV1(params, globalBean.getAlipayPublicKey(), globalBean.getCharset(), globalBean.getSignType());
        } catch (AlipayApiException e) {
            //处理异常跳转错误页面什么的
            throw new RuntimeException(e);
        }
        System.out.println(JSON.toJSONString(params));
        //获取用户自己的订单号
        String outTradeNo = params.get("out_trade_no");
        //处理自身业务逻辑，比如修改订单为完成，给用户增加积分什么的

        //通常这里会返回一个支付成功页面，给前端展示
    }

    @RequestMapping("notifyAlipay")
    public void notifyAlipay(HttpServletRequest request,HttpServletResponse resp) throws AlipayApiException, IOException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<String> strings = parameterMap.keySet();
        Map<String,String> params = new HashMap<>();
        strings.forEach(o->{
            params.put(o,String.join(",", parameterMap.get(o)));
        });
        System.out.println(JSON.toJSONString(parameterMap));
        boolean rsaCheckV1 = AlipaySignature.rsaCheckV1(params, globalBean.getAlipayPublicKey(), globalBean.getCharset(), globalBean.getSignType());
        if (!rsaCheckV1){
            //校验失败返回内容..
            return;
        }
        //校验成功则 获取用户自己的订单号，比如修改订单为完成，给用户增加积分什么的
        String outTradeNo = params.get("out_trade_no");
        if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {
            //表示支付成功 执行支付成功的逻辑
        } else if ("TRADE_CLOSED".equals(params.get("trade_status"))) {//订单过期则关闭订单
            //表示支付超时或者关闭，执行失败的逻辑
        }
        //返回结果，异步通知需要返回success，支付宝检测到success后则停止异步请求，否则会轮询请求。
        resp.getWriter().write("success");
        resp.getWriter().flush();
        resp.getWriter().close();
    }

}
